package com.rzico.sbl.ui.member

import android.view.View
import android.widget.CompoundButton
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberOfflineBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.BillWorkerData
import com.rzico.sbl.other.showOfflineWindow
import com.rzico.sbl.ui.mine.ShopModifyActivity
import com.rzico.sbl.viewmodel.MemberViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.helper.getString
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class MemberOfflineActivity : BaseActivity(R.layout.activity_member_offline) {

    private val mBinding by lazy { ActivityMemberOfflineBinding.bind(getRootView()) }

    private var isEditMode = false

    override fun getViewModel() = get<MemberViewModel>()

    override fun initData() {
        initTitle(title = "休眠会员")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.apply {
            offlineAll.setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

            listLayout.apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关会员信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<BillWorkerData>(R.layout.item_offline_list) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_offline_name, "${bean.name}  ${bean.mobile}")
                                text(R.id.item_offline_time, bean.last_order_day)
                                text(R.id.item_offline_borrow, bean.borrow)
                                text(R.id.item_offline_adress, bean.address)
                                text(R.id.item_offline_visit, bean.last_visit_day)
                                text(R.id.item_offline_count, bean.visit)

                                getView<View>(R.id.item_offline_adress)
                                    .isGone = bean.address.isNullOrEmpty()
                                getView<ImageView>(R.id.item_offline_img)
                                    .loadCircleImage(
                                        bean.logo,
                                        R.mipmap.default_user
                                    )

                                with<ImageView>(R.id.item_offline_check) {
                                    it.isVisible = isEditMode
                                    it.setImageResource(
                                        conditionIf(
                                            bean.check,
                                            R.mipmap.login_yes_orange,
                                            R.mipmap.login_no
                                        )
                                    )
                                }

                                clicked(R.id.item_offline_img) {
                                    startActivityEx<MemberDetailActivity>(
                                        "cardId" to bean.id,
                                        "memberId" to bean.member,
                                        "memberPhone" to bean.mobile
                                    )
                                }

                                clicked(R.id.item_offline_call) {
                                    bean.mobile.notEmpty {
                                        showBottomPhoneDialog(this)
                                    }
                                }

                                clicked {
                                    if (isEditMode) {
                                        bean.check = !bean.check
                                        notifyItemChanged(index)

                                        checkTextHint()
                                    } else {
                                        startActivityEx<MemberOfflineRecordActivity>(
                                            "cardId" to bean.id
                                        )
                                    }
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }

            ivRight?.let { iv ->
                iv.isVisible = true
                iv.setPadding(dp2px(11f), 0, dp2px(11f), 0)
                iv.setImageResource(R.drawable.ic_more_right_white)

                iv.oneClick {
                    showOfflineWindow(
                        anchor = iv,
                        isEdit = isEditMode,
                        onSelect = { index ->
                            when (index) {
                                0 -> {
                                    isEditMode = !isEditMode
                                    offlineBottom.isVisible = isEditMode

                                    if (isEditMode) {
                                        mList.forEach {
                                            it as BillWorkerData
                                            it.check = false
                                        }

                                        checkTextHint()
                                    }

                                    mAdapter.notifyDataSetChanged()
                                }

                                1 ->
                                    startActivityEx<ShopModifyActivity>(
                                        "title" to "修改店铺",
                                        "status" to "edit",
                                        "shopId" to getString("shopId")
                                    )
                            }
                        }
                    )
                }
            }
        }
    }

    override fun initListener() {
        mBinding.apply {
            offlineCancel.oneClick {
                mList.forEach {
                    it as BillWorkerData
                    it.check = false
                }

                mAdapter.notifyDataSetChanged()

                checkTextHint()
            }

            offlineSure.oneClick {
                if (mList.none { (it as BillWorkerData).check }) {
                    showToast("请选择要提醒的会员")
                    return@oneClick
                }

                getViewModel()
                    .requestBind(
                        requestUrl = BaseUrl.mngPush,
                        params = arrayOf(
                            "type" to "2",
                            "ids" to mList
                                .filter { (it as BillWorkerData).check }
                                .joinToString(",") { (it as BillWorkerData).id }
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("提醒成功！")

                            isEditMode = false
                            tvRight?.text = "批量"
                            offlineBottom.isVisible = isEditMode

                            mAdapter.notifyDataSetChanged()
                        }
                    )
            }
        }

        // 监听店铺信息修改
        observe<String>("shopList") { updateList() }
    }

    /**
     * 休眠会员列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .offlineList(
                page = index,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)

                    if (isEditMode) checkTextHint()
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    private fun checkTextHint() {
        mBinding.apply {
            offlineAll
                .apply {
                    setOnCheckedChangeListener(null)
                    isChecked =
                        mList.isNotEmpty() && mList.none { !(it as BillWorkerData).check }
                    setOnCheckedChangeListener(this@MemberOfflineActivity)
                }

            offlineSure.text = "提醒(${mList.count { (it as BillWorkerData).check }})"
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { (it as BillWorkerData).check = isChecked }
        mAdapter.notifyDataSetChanged()

        checkTextHint()
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}